﻿using System;
using System.Collections.Concurrent;
using System.Web;
using System.Web.Mvc;
using Inovout.Data.Repository;
using Inovout.Serializer;
using Newtonsoft.Json;

namespace Inovout.Web.Mvc
{
    public class JsonNetResult:JsonResult
    {
        public Type ContainerType { get;set; }
        
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                response.Write(JsonNetSerializer.Serialize(Data,CreateJsonSerializerSettings( ContainerType??Data.GetType())));
            }
        }
        private static readonly ConcurrentDictionary<Type, JsonSerializerSettings> JsonSerializerSettingsCache = new ConcurrentDictionary<Type, JsonSerializerSettings>();
        private static JsonSerializerSettings CreateJsonSerializerSettings(Type type)
        {

            return
                 JsonSerializerSettingsCache.GetOrAdd(type, (t) =>
                 {
                     JsonSerializerSettings settings = new JsonSerializerSettings();
                     settings.ContractResolver = new NHibernateContractResolver(type);
                     return settings;
                 });
        }
    }
}
